package com.skali.hooks;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.documentlibrary.NoSuchFileEntryMetadataException;
import com.liferay.portlet.documentlibrary.model.DLFileEntry;
import com.liferay.portlet.documentlibrary.model.DLFileEntryMetadata;
import com.liferay.portlet.documentlibrary.model.DLFileEntryType;
import com.liferay.portlet.documentlibrary.service.DLFileEntryLocalService;
import com.liferay.portlet.documentlibrary.service.DLFileEntryLocalServiceWrapper;
import com.liferay.portlet.documentlibrary.service.DLFileEntryMetadataLocalServiceUtil;
import com.liferay.portlet.documentlibrary.service.DLFileEntryTypeLocalServiceUtil;
import com.liferay.portlet.dynamicdatamapping.model.DDMStructure;
import com.liferay.portlet.dynamicdatamapping.storage.Fields;
import com.liferay.portlet.dynamicdatamapping.storage.StorageEngineUtil;
import com.skali.cab.CABDirectoriesBean;
import com.skali.cabdirectories.NoSuchCABDirectory_DLFileEntryMappingException;
import com.skali.cabdirectories.model.CABDirectories_Metadata;
import com.skali.cabdirectories.model.CABDirectory_DLFileEntryMapping;
import com.skali.cabdirectories.service.CABDirectories_MetadataLocalServiceUtil;
import com.skali.cabdirectories.service.CABDirectory_DLFileEntryMappingLocalServiceUtil;
import com.skali.portal.util.Constants;

public class ExtDLFileEntryLocalService extends DLFileEntryLocalServiceWrapper {
	/* (non-Java-doc)
	 * @see com.liferay.portlet.documentlibrary.service.DLFileEntryLocalServiceWrapper#DLFileEntryLocalServiceWrapper(DLFileEntryLocalService dlFileEntryLocalService)
	 */
	public ExtDLFileEntryLocalService(DLFileEntryLocalService dlFileEntryLocalService) {
		super(dlFileEntryLocalService);
	}
	

	/**@author Prabhakar
	 * 
	 * 	This Method checks whenever the DL File Entry is Added ...&& we need to add the same ref in our custom  entity...
	 */	
	@Override
	public DLFileEntry addFileEntry(long userId, long groupId,
			long repositoryId, long folderId, String sourceFileName,
			String mimeType, String title, String description,
			String changeLog, long fileEntryTypeId,
			Map<String, Fields> fieldsMap, File file, InputStream is,
			long size, ServiceContext serviceContext) throws PortalException,
			SystemException {
		// TODO Auto-generated method stub

		String fileType = StringPool.BLANK;
		DLFileEntry dlFileEntry = null;

		try{

			dlFileEntry =  super.addFileEntry(userId, groupId, repositoryId, folderId,
					sourceFileName, mimeType, title, description, changeLog,
					fileEntryTypeId, fieldsMap, file, is, size, serviceContext);

			fileType = DLFileEntryTypeLocalServiceUtil.getDLFileEntryType(fileEntryTypeId).getName();
			System.out.println(fileType +" Type Doc Entry Found ...!!!");

			/**
			 * our custom method-Call for every Doc-Type - 'ACB' ..
			 */
			if(fileType.equalsIgnoreCase(Constants.ACB)){
				System.out.println(" getFileEntryId >> "+dlFileEntry.getFileEntryId()+" getFileEntryTypeId >> "+dlFileEntry.getFileEntryTypeId() );
				getFileEntryMetadata(dlFileEntry);

			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return dlFileEntry;
	}


	/**@author Prabhakar
	 * 
	 * 	This Method checks whenever the DL File Entry is Updated ...&& we need to update the same ref in our custom  entity...
	 */	
	@Override
	public DLFileEntry updateFileEntry(long userId, long fileEntryId,
			String sourceFileName, String mimeType, String title,
			String description, String changeLog, boolean majorVersion,
			long fileEntryTypeId, Map<String, Fields> fieldsMap, File file,
			InputStream is, long size, ServiceContext serviceContext)
			throws PortalException, SystemException {
		// TODO Auto-generated method stub
		
		String fileType = StringPool.BLANK;
		DLFileEntry dlFileEntry = null;
		try{
		 dlFileEntry = super.updateFileEntry(userId, fileEntryId, sourceFileName, mimeType,
					title, description, changeLog, majorVersion, fileEntryTypeId,
					fieldsMap, file, is, size, serviceContext);
		 
		System.out.println(" INSIDE updateDLFileEntry 3...");
		
		fileType = DLFileEntryTypeLocalServiceUtil.getDLFileEntryType(fileEntryTypeId).getName();
		System.out.println(fileType +" Type Doc Entry Found ...!!!");

		/**
		 * our custom method-Call for every Doc-Type - 'ACB' ..
		 */
		if(fileType.equalsIgnoreCase(Constants.ACB)){
			System.out.println(" getFileEntryId >> "+dlFileEntry.getFileEntryId()+" getFileEntryTypeId >> "+dlFileEntry.getFileEntryTypeId() );
			getFileEntryMetadata(dlFileEntry);

		}
		}catch(Exception e){
			System.out.println(" inside excep 11 >>> ");
			e.printStackTrace();
		}

		return dlFileEntry;
	}

	
	
	/** @author Prabhakar
	 * our custom method that Fetches the FileEntryMetadata 
	 * @param fileEntryId 
	 * @Params-FileEntryTypeId
	 * @Params-FileVersionId
	 */
	public void getFileEntryMetadata(DLFileEntry dlFileEntry) throws PortalException,
			SystemException {
		
		long fileEntryId = dlFileEntry.getFileEntryId();
		long fileEntryTypeId = dlFileEntry.getFileEntryTypeId();
		long fromFileVersionId = dlFileEntry.getFileVersion().getFileVersionId();
		 
		CABDirectoriesBean cabDirectoriesBean = new CABDirectoriesBean();
	
		System.out.println(" >>>  inside getFileEntryMetadata <<< ");
		System.out.println( "fileEntryId= "+fileEntryId+" fileEntryTypeId = "+fileEntryTypeId+" fromFileVersionId = "+fromFileVersionId);
		final String filePath_UptoDM = "documents/"+dlFileEntry.getGroupId()+"/"+dlFileEntry.getFolderId()+"/"+dlFileEntry.getTitle();
		System.out.println(">>>>>>  filePath_UptoDM >>> = "+filePath_UptoDM);
		
		if(fileEntryTypeId>0){
			
			DLFileEntryType dlFileEntryType = DLFileEntryTypeLocalServiceUtil.fetchDLFileEntryType(fileEntryTypeId);
			List<DDMStructure> ddmStructures = new ArrayList<DDMStructure>();
			ddmStructures =	dlFileEntryType.getDDMStructures();
			System.out.println(" ddmStructures -size == "+ddmStructures.size());
			
			cabDirectoriesBean.setFileEntryId(fileEntryId);
			cabDirectoriesBean.setFileEntryTypeId(fileEntryTypeId);
			cabDirectoriesBean.setType_(dlFileEntryType.getName());
			cabDirectoriesBean.setScope(filePath_UptoDM);
			
			if(ddmStructures.size()>0){
				for (DDMStructure ddmStructure : ddmStructures) {
					try {
						DLFileEntryMetadata fileEntryMetadata =
								DLFileEntryMetadataLocalServiceUtil.getFileEntryMetadata(ddmStructure.getStructureId(), fromFileVersionId);

						Fields fields = StorageEngineUtil.getFields(
								fileEntryMetadata.getDDMStorageId());

						Iterator<String> iterator = fields.getNames(). iterator();
						while(iterator.hasNext()){

							String key = iterator.next();
							String fieldValue = fields.get(key).getValue().toString();
							System.out.println(" key = "+key);
							System.out.println(" value = "+fieldValue);
							System.out.println("!fieldValue.isEmpty() = "+!fieldValue.isEmpty());
							System.out.println("\n ---------------------------------");
						
							if(key.equalsIgnoreCase(Constants.OrganizationName) && !fieldValue.isEmpty()) cabDirectoriesBean.setOrganizationName(fieldValue);
							if(key.equalsIgnoreCase(Constants.Field) && !fieldValue.isEmpty()) cabDirectoriesBean.setField(fieldValue);
							if(key.equalsIgnoreCase(Constants.Program) && !fieldValue.isEmpty()) cabDirectoriesBean.setProgram(fieldValue);
							if(key.equalsIgnoreCase(Constants.Status) && !fieldValue.isEmpty()) cabDirectoriesBean.setStatus(fieldValue);
							if(key.equalsIgnoreCase(Constants.SubStatus) && !fieldValue.isEmpty()) cabDirectoriesBean.setSubStatus(fieldValue);
							if(key.equalsIgnoreCase(Constants.Address) && !fieldValue.isEmpty()) cabDirectoriesBean.setAddress(fieldValue);
							if(key.equalsIgnoreCase(Constants.Contact) && !fieldValue.isEmpty()) cabDirectoriesBean.setContact(fieldValue);
							if(key.equalsIgnoreCase(Constants.Email) && !fieldValue.isEmpty()) cabDirectoriesBean.setEmail(fieldValue);
							if(key.equalsIgnoreCase(Constants.Website) && !fieldValue.isEmpty()) cabDirectoriesBean.setWebsite(fieldValue);
							if(key.equalsIgnoreCase(Constants.OfficerInCharge) && !fieldValue.isEmpty()) cabDirectoriesBean.setOfficerInCharge(fieldValue);
							if(key.equalsIgnoreCase(Constants.EmailOfficeIncharge) && !fieldValue.isEmpty()) cabDirectoriesBean.setEmailOfficeIncharge(fieldValue);
							if(key.equalsIgnoreCase(Constants.Tel) && !fieldValue.isEmpty()) cabDirectoriesBean.setTel(Long.valueOf(fieldValue));
							if(key.equalsIgnoreCase(Constants.Fax) && !fieldValue.isEmpty()) cabDirectoriesBean.setFax(Long.valueOf(fieldValue));
							if(key.equalsIgnoreCase(Constants.TelephoneNo) && !fieldValue.isEmpty()) cabDirectoriesBean.setTelephoneNo(Long.valueOf(fieldValue));
							if(key.equalsIgnoreCase(Constants.StandardsUsed) && !fieldValue.isEmpty()) cabDirectoriesBean.setStandardsUsed(fieldValue);
							
						}

						/**
						 * our custom method that updates the Entity CabDirectories_Metadata..
						 */
						updateCabDirectoriesMetadata(cabDirectoriesBean);

					}
					catch (NoSuchFileEntryMetadataException nsfeme) {
					}
				}
			}
		}
				
	}

	
	/** @author Prabhakar
	 * our custom method that updates the CabDirectoriesMetadata entity 
	 * against each of our CustomDoc added in DlFile-Entry
	 * ..........
	 * Params-cabDirectoriesBean
	 */
	private void updateCabDirectoriesMetadata(CABDirectoriesBean cabDirectoriesBean) {
		
		long SammNo =0;
		CABDirectories_Metadata cabDirectories_Metadata = null;
		CABDirectory_DLFileEntryMapping	cabDirectory_DLFileEntryMapping = null;
		try {
			
			System.out.println("Inside updateCabDirectoriesMetadata <<< ");
			try{
				cabDirectory_DLFileEntryMapping = CABDirectory_DLFileEntryMappingLocalServiceUtil.findByFileEntryId(cabDirectoriesBean.getFileEntryId());
			} catch (NoSuchCABDirectory_DLFileEntryMappingException e) {
				System.out.println(" caught --NoSuchCABDirectory_DLFileEntryMappingException");
				//	Incase Mapping already Exists--calls for only an UPdate rather than a new Metadata Entry..
				SammNo = CounterLocalServiceUtil.increment(CABDirectories_Metadata.class.getName());
				cabDirectories_Metadata =  CABDirectories_MetadataLocalServiceUtil.createCABDirectories_Metadata(SammNo);
			}

			if(Validator.isNotNull(cabDirectory_DLFileEntryMapping)){
				System.out.println(" Inside if 121 cabDirectory_DLFileEntryMapping isNotNull--");
				SammNo = cabDirectory_DLFileEntryMapping.getSammId();
				cabDirectories_Metadata =  CABDirectories_MetadataLocalServiceUtil.getCABDirectories_Metadata(SammNo);
			}
			
			System.out.println(" getOrganizationName values recevd in Bean = "+cabDirectoriesBean.getOrganizationName());
			System.out.println(" getEmail values recevd in Bean = "+cabDirectoriesBean.getEmail());
			System.out.println(" getSubStatus values recevd in Bean = "+cabDirectoriesBean.getSubStatus());
			System.out.println(" getEmailOfficeIncharge values recevd in Bean = "+cabDirectoriesBean.getEmailOfficeIncharge());
			System.out.println(" getOfficerInCharge values recevd in Bean = "+cabDirectoriesBean.getOfficerInCharge());
			System.out.println(" getStandardsUsed values recevd in Bean = "+cabDirectoriesBean.getStandardsUsed());
			
			cabDirectories_Metadata.setOrganizationName(cabDirectoriesBean.getOrganizationName());
			cabDirectories_Metadata.setField(cabDirectoriesBean.getField());
			cabDirectories_Metadata.setStatus(cabDirectoriesBean.getStatus());
			cabDirectories_Metadata.setSubStatus(cabDirectoriesBean.getSubStatus());
			cabDirectories_Metadata.setAddress(cabDirectoriesBean.getAddress());
			cabDirectories_Metadata.setContact(cabDirectoriesBean.getContact());
			cabDirectories_Metadata.setTel(cabDirectoriesBean.getTel());
			cabDirectories_Metadata.setFax(cabDirectoriesBean.getFax());
			cabDirectories_Metadata.setProgram(cabDirectoriesBean.getProgram());
			cabDirectories_Metadata.setEmail(cabDirectoriesBean.getEmail());
			cabDirectories_Metadata.setWebsite(cabDirectoriesBean.getWebsite());
			cabDirectories_Metadata.setType_(cabDirectoriesBean.getType_());
			cabDirectories_Metadata.setScope(cabDirectoriesBean.getScope());
			cabDirectories_Metadata.setOfficerInCharge(cabDirectoriesBean.getOfficerInCharge());
			cabDirectories_Metadata.setTelephoneNo(cabDirectoriesBean.getTelephoneNo());
			cabDirectories_Metadata.setEmailOfficeIncharge(cabDirectoriesBean.getEmailOfficeIncharge());
			cabDirectories_Metadata.setStandardsUsed(cabDirectoriesBean.getStandardsUsed());

			if(Validator.isNull(cabDirectory_DLFileEntryMapping)){
				CABDirectories_MetadataLocalServiceUtil.addCABDirectories_Metadata(cabDirectories_Metadata);
				System.out.println("CABDirectories_MetadataLocalServiceUtil.addCABDirectories_Metadata <<< ");
				/**
				 *Incase of a new cabDirectories_Metadata Entry need to call another custom method that does cabDirectory_DLFileEntryMapping Entry as well ...
				 */
				updateCABDirectory_DLFileEntryMapping(cabDirectoriesBean , SammNo);

			}else{
				CABDirectories_MetadataLocalServiceUtil.updateCABDirectories_Metadata(cabDirectories_Metadata);
				
				System.out.println("Inside CABDirectories_MetadataLocalServiceUtil--updateCABDirectories_Metadata <<< ");
			}


		} catch (SystemException e) {
			System.out.println(" caught --SystemException 12");
			e.printStackTrace();
		} catch (PortalException e) {
			System.out.println(" caught --PortalException 12");
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	
	/** @author Prabhakar
	 * our custom method that updates the CABDirectory_DLFileEntryMapping entity 
	 * thats holds the mapping relation b/w the DL_File ENtry && our CABDirectories_Metadata Entity
	 * ..........
	 * Params-cabDirectoriesBean
	 * Params - sammNo
	 */
	private void updateCABDirectory_DLFileEntryMapping(
			CABDirectoriesBean cabDirectoriesBean, long sammNo) {

		CABDirectory_DLFileEntryMapping cabDirectory_DLFileEntryMapping = null;
		
		System.out.println("Inside updateCABDirectory_DLFileEntryMapping <<< ");
		try {
			
			if(Validator.isNotNull(sammNo)&& Validator.isNotNull(cabDirectoriesBean)){
				System.out.println(" inside if 5500");
				long mappingId = CounterLocalServiceUtil.increment(CABDirectory_DLFileEntryMapping.class.getName());
				cabDirectory_DLFileEntryMapping = CABDirectory_DLFileEntryMappingLocalServiceUtil.createCABDirectory_DLFileEntryMapping(mappingId);
				cabDirectory_DLFileEntryMapping.setSammId(sammNo);
				cabDirectory_DLFileEntryMapping.setDlFileEntryId(cabDirectoriesBean.getFileEntryId());
				CABDirectory_DLFileEntryMappingLocalServiceUtil.addCABDirectory_DLFileEntryMapping(cabDirectory_DLFileEntryMapping);
			}else{
				/**
				 * In case of update DLFileEntry-- No need of Entry in cabDirectory_DLFileEntryMapping...
				 */
				System.out.println(" inside else 5500");
			}

		} catch (SystemException e) {
			System.out.println(" caught --SystemException 55");
			e.printStackTrace();
		} 

	}
	
	
	/**	@author Prabhakar
	 * 	This Method checks whenever the DL File Entry is deleted ...&& we need to delete the same ref in our custom  entity...
	 * params-@ userId
	 * params-@ fileEntryId
	 */
	@Override
	public void deleteFileEntry(long userId, long fileEntryId)
			throws PortalException, SystemException {
		// TODO Auto-generated method stub
		System.out.println(" ###  INSIDE deleteDLFileEntry 4...");
		super.deleteFileEntry(userId, fileEntryId);
	
		delete_CabDirectories_Metadata(fileEntryId);
	
	}

	/** @author Prabhakar
	 * our custom method that deletes CabDirectories_Metadata entity 
	 * thats holds the mapping relation b/w the DL_File ENtry && our CABDirectories_Metadata Entity
	 * ..........
	 * Params-fileEntryId
	 */
	private void delete_CabDirectories_Metadata(long fileEntryId) {

		CABDirectory_DLFileEntryMapping cabDirectory_DLFileEntryMapping = null;
		try {
			cabDirectory_DLFileEntryMapping = CABDirectory_DLFileEntryMappingLocalServiceUtil.findByFileEntryId(fileEntryId);
			
			// deletes the CABDirectories_Metadata object...
			CABDirectories_MetadataLocalServiceUtil.deleteCABDirectories_Metadata(cabDirectory_DLFileEntryMapping.getSammId());
		
			// deletes the CABDirectory_DLFileEntryMapping object...
			CABDirectory_DLFileEntryMappingLocalServiceUtil.deleteCABDirectory_DLFileEntryMapping(cabDirectory_DLFileEntryMapping);
			
		} catch (NoSuchCABDirectory_DLFileEntryMappingException e) {
			e.printStackTrace();
		} catch (SystemException e) {
			e.printStackTrace();
		}catch (PortalException e) {
			e.printStackTrace();
		}

	}


	@Override
	public DLFileEntry deleteDLFileEntry(DLFileEntry dlFileEntry)
			throws SystemException {
		// TODO Auto-generated method stub
		System.out.println(" INSIDE deleteDLFileEntry 1...");
		return super.deleteDLFileEntry(dlFileEntry);
	}

	@Override
	public DLFileEntry deleteDLFileEntry(long fileEntryId)
			throws PortalException, SystemException {
		// TODO Auto-generated method stub
		System.out.println(" INSIDE deleteDLFileEntry 2...");
		return super.deleteDLFileEntry(fileEntryId);
	}

	@Override
	public void deleteFileEntries(long groupId, long folderId)
			throws PortalException, SystemException {
		// TODO Auto-generated method stub
		System.out.println(" INSIDE deleteDLFileEntry 3...");
		super.deleteFileEntries(groupId, folderId);
	}
	
	@Override
	public void deleteFileEntry(long fileEntryId) throws PortalException,
			SystemException {
		// TODO Auto-generated method stub
		System.out.println(" INSIDE deleteDLFileEntry 5...");
		super.deleteFileEntry(fileEntryId);
	}

	
	
	
	@Override
	public void checkInFileEntry(long userId, long fileEntryId,
			boolean majorVersion, String changeLog,
			ServiceContext serviceContext) throws PortalException,
			SystemException {
		// TODO Auto-generated method stub
		System.out.println(" INSIDE checkInFileEntry 1...");
		
		super.checkInFileEntry(userId, fileEntryId, majorVersion, changeLog,
				serviceContext);
	}

	@Override
	public void checkInFileEntry(long userId, long fileEntryId, String lockUuid)
			throws PortalException, SystemException {
		// TODO Auto-generated method stub
		System.out.println(" INSIDE checkInFileEntry 2...");
		
		super.checkInFileEntry(userId, fileEntryId, lockUuid);
	}

	@Override
	public DLFileEntry updateDLFileEntry(DLFileEntry dlFileEntry, boolean merge)
			throws SystemException {
		// TODO Auto-generated method stub
		
		System.out.println(" INSIDE updateDLFileEntry 1...");
		return super.updateDLFileEntry(dlFileEntry, merge);
	}

	@Override
	public DLFileEntry updateDLFileEntry(DLFileEntry dlFileEntry)
			throws SystemException {
		// TODO Auto-generated method stub
		
		System.out.println(" INSIDE updateDLFileEntry 2...");
		return super.updateDLFileEntry(dlFileEntry);
	}

}